import {
  BottomSheetModal,
  BottomSheetTextInput,
  BottomSheetView,
} from '@gorhom/bottom-sheet';
import React, {
  ForwardRefExoticComponent,
  ForwardRefRenderFunction,
  useCallback,
  useEffect,
  useRef,
  useState,
  useTransition,
} from 'react';
import CustomBottomSheetBackdrop from './CustomBottomSheetBackdrop';
import { ActivityIndicator, Text, TouchableOpacity, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import Slider, { SliderRef } from '@react-native-community/slider';
import { stationApi, StationInverter } from '@/services/api/stationApi';
import { Button, useAppTheme } from 'tsun-smart-ui';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

type InverterEditBottomSheetProps = {
  inverter?: StationInverter | null;
  onUpdate: (inverter: StationInverter) => void;
};

const InverterEditBottomSheet = React.forwardRef<
  BottomSheetModal,
  InverterEditBottomSheetProps
>((props, ref) => {
  const { t } = useTranslation();
  const appTheme = useAppTheme();
  const safeAreaInsets = useSafeAreaInsets();
  const [inverter, setInverter] = useState<StationInverter | null | undefined>(
    props.inverter
  );
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setInverter(props.inverter);
  }, [props.inverter]);

  const onSave = useCallback(() => {
    if (inverter) {
      setLoading(true);
      stationApi
        .updateStationInverter({
          ratePowerReal: inverter.ratePowerReal,
          ratePower: inverter.ratePower,
          ratePowerFactor: inverter.ratePowerFactor,
          deviceSn: inverter.deviceSn,
        })
        .then((newInverter) => {
          // @ts-ignore
          ref?.current?.dismiss();
          setLoading(false);
          props.onUpdate(newInverter.data);
        })
        .catch(() => {
          setLoading(true);
        });
    }
  }, [inverter, props.inverter, props.onUpdate]);

  const onChangeText = useCallback(
    (text: string) => {
      const numberText = text.replaceAll(/[^\d]/g, '');
      const inputPower = parseInt(numberText, 10);
      const resolvedInputPower = isNaN(inputPower) ? 0 : inputPower;
      const maxRate = inverter?.ratePower ?? 0;
      setInverter((prev) => {
        if (prev) {
          return {
            ...prev,
            ratePowerReal: Math.min(resolvedInputPower, maxRate),
          };
        }
        return undefined;
      });
    },
    [inverter]
  );

  const onCancel = useCallback(() => {
    // @ts-ignore
    ref?.current?.dismiss();
  }, [props.inverter]);

  const maxLength = inverter?.ratePower?.toString()?.length ?? 4;

  return (
    <>
      <BottomSheetModal
        ref={ref}
        backdropComponent={CustomBottomSheetBackdrop}
        enablePanDownToClose
        handleStyle={{
          backgroundColor: appTheme.colors?.background?.primary,
          borderTopLeftRadius: 16,
          borderTopRightRadius: 16,
        }}
        backgroundStyle={{
          backgroundColor: appTheme.colors?.background?.primary,
        }}
        activeOffsetY={50}
        keyboardBlurBehavior="restore"
        enableBlurKeyboardOnGesture
        android_keyboardInputMode="adjustPan"
      >
        <BottomSheetView
          className="px-4 py-4 items-stretch"
          style={{ marginBottom: safeAreaInsets.bottom + 24 }}
        >
          <View className="flex-row items-center gap-3 mb-4">
            <Text className="text-[16px] text-text1 font-medium">
              {t('user.power_regulation')}
            </Text>
            <View className="flex-1" />
            <BottomSheetTextInput
              className="bg-fill3 rounded-xl w-28 min-h-10 text-[16px] font-medium text-center text-text1"
              keyboardType="number-pad"
              value={`${inverter?.ratePowerReal ?? 0}`}
              onChangeText={onChangeText}
              selectTextOnFocus
              maxLength={maxLength}
            />
            <Text className="text-text1 text-[16px] font-medium">W</Text>
          </View>
          <Slider
            minimumValue={0}
            maximumValue={inverter?.ratePower || 0}
            step={100}
            value={inverter?.ratePowerReal || 0}
            onValueChange={(value) => {
              setInverter((prev) => {
                if (prev) {
                  return {
                    ...prev,
                    ratePowerReal: value,
                  };
                }
                return undefined;
              });
            }}
            thumbTintColor={appTheme.colors?.brand?.onPrimary}
            minimumTrackTintColor={appTheme.colors?.brand?.primary}
            maximumTrackTintColor={appTheme.colors?.border?.primary}
          />
          <View className="flex-row items-center justify-between">
            <Text className="text-text2 text-[14px]">0</Text>
            <Text className="text-text2 text-[14px]">
              {inverter?.ratePower || 0}
            </Text>
          </View>
          <Text className="text-[12px] text-text2 mt-4">
            {t('sys.app.user.can.modify.power')}
          </Text>
          <View
            className="flex-row gap-4 h-12 items-stretch mt-8"
            style={{ marginBottom: safeAreaInsets.bottom }}
          >
            <TouchableOpacity
              className="flex-1 bg-fill3 rounded-full items-center justify-center"
              onPress={onCancel}
            >
              <Text className="text-text2 text-[16px] leading-4">
                {t('user.logOutCancel')}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              className="flex-1 rounded-full items-center justify-center flex-row gap-2"
              style={{
                backgroundColor: loading
                  ? appTheme.colors?.brand?.primaryDisabled
                  : appTheme.colors?.brand?.primary,
              }}
              onPress={onSave}
              disabled={loading}
            >
              {loading && <ActivityIndicator size={'small'} color={'white'} />}
              <Text className="text-white text-[16px] leading-4">
                {t('userSetting.save')}
              </Text>
            </TouchableOpacity>
          </View>
        </BottomSheetView>
      </BottomSheetModal>
    </>
  );
});

export default React.memo(InverterEditBottomSheet);
